package com.zh.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zh.common.ErrorCode;
import com.zh.domain.Model.ws.SimpleAttacheModel;
import com.zh.domain.Model.ws.SimpleUserModel;
import com.zh.domain.dto.requirement.AddRequirementCommentRequest;
import com.zh.domain.dto.requirement.PageReqCommentRequest;
import com.zh.domain.entity.Message;
import com.zh.domain.entity.ReqComments;
import com.zh.domain.vo.requirement.RequirementCommentVo;
import com.zh.domain.vo.requirement.RequirementVo;
import com.zh.domain.vo.user.UserVO;
import com.zh.exception.ThrowUtils;
import com.zh.job.TaskManager;
import com.zh.service.*;
import com.zh.mapper.ReqCommentsMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 针对表【req_comments(需求评论表)】的数据库操作Service实现
 * @createDate 2025-02-09 16:24:10
 */
@Service
public class ReqCommentsServiceImpl extends ServiceImpl<ReqCommentsMapper, ReqComments>
        implements ReqCommentsService {
    @Resource
    private ReqCommentsMapper reqCommentsMapper;
    @Resource
    private UserService userService;
    @Resource
    private MessageService messageService;
    @Resource
    private RequirementsService requirementsService;
    private static final String attacheKey = "A";
    private static final String atUserKey = "M";

    @Override
    public Boolean addReqComment(AddRequirementCommentRequest addRequirementCommentRequest) {
        int loginId = StpUtil.getLoginIdAsInt();
        // 参数校验
        Integer taskId = addRequirementCommentRequest.getReqId();
        Integer sendId = addRequirementCommentRequest.getSendId();
        String content = addRequirementCommentRequest.getContent();
        List<SimpleAttacheModel> attacheList = addRequirementCommentRequest.getAttacheList();
        List<Integer> atUserList = addRequirementCommentRequest.getAtUserList();
        ThrowUtils.throwIf(taskId == null, ErrorCode.PARAMS_ERROR, "需求id不能为空");
        if (sendId == null) {
            sendId = loginId;
        }
        //2.拼装 附件、@人信息
        Map<String, Object> params = new HashMap<>();

        if (attacheList != null) {
            params.put(attacheKey, JSONUtil.toJsonStr(attacheList));
        }
        if (atUserList != null) {
            List<UserVO> userVOList = userService.listUserVoByIds(atUserList);
            List<SimpleUserModel> simpleUserModelList = userVOList.stream().map(userVO -> {
                SimpleUserModel simpleUserModel = new SimpleUserModel();
                simpleUserModel.setId(userVO.getId());
                simpleUserModel.setName(userVO.getName());
                simpleUserModel.setAvatar(userVO.getAvatar());
                return simpleUserModel;
            }).collect(Collectors.toList());
            params.put(atUserKey, JSONUtil.toJsonStr(simpleUserModelList));
        }
        //3.插入数据库
        ReqComments reqComments = BeanUtil.copyProperties(addRequirementCommentRequest, ReqComments.class);
        reqComments.setSendId(sendId);
        reqComments.setParams(params);
        reqComments.setCreateAt(LocalDateTime.now());
        reqComments.setCreateBy(loginId);
        reqComments.setUpdateAt(LocalDateTime.now());
        reqComments.setUpdateBy(loginId);
        reqComments.setStatus(1);
        reqComments.setDeleted(0);
        boolean success = reqCommentsMapper.insert(reqComments) > 0;
        //4.发送消息给被@人
        TaskManager.execute(() -> sendMessageWhenAdd(loginId, reqComments, atUserList));
        return success;
    }

    @Override
    public void sendMessageWhenAdd(int sendId, ReqComments reqComments, List<Integer> revciverList) {
        Message message = new Message();
        message.setSendId(sendId);
        message.setContent(reqComments.getContent());
        message.setCreateBy(sendId);
        message.setUpdateBy(sendId);
        message.setCreateAt(LocalDateTime.now());
        message.setUpdateAt(LocalDateTime.now());
        message.setNoticeType(3);
        message.setType(1);
        RequirementVo requirementVo = requirementsService.getDetail(reqComments.getReqId());
        message.setParams(Map.of(
                "reqId", reqComments.getReqId().toString(),
                "payloadType", "requirement",
                "title", requirementVo.getTitle()
        ));
        messageService.sendMessage(message, revciverList);
    }

    @Override
    public Page<RequirementCommentVo> pageReqComment(PageReqCommentRequest pageReqCommentRequest) {
        Integer reqId = pageReqCommentRequest.getReqId();
        ThrowUtils.throwIf(null == reqId, ErrorCode.PARAMS_ERROR, "需求Id不能为空");
        pageReqCommentRequest.standardizeSize();
        Integer current = pageReqCommentRequest.getCurrent();
        Integer pageSize = pageReqCommentRequest.getPageSize();
        Page<ReqComments> page = new Page<>(current, pageSize);
        LambdaQueryWrapper<ReqComments> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ReqComments::getReqId, reqId)
                .orderByDesc(ReqComments::getCreateAt)
                .orderByDesc(ReqComments::getId);
        Page<ReqComments> taskCommentsPage = reqCommentsMapper.selectPage(page, queryWrapper);
        List<ReqComments> records = taskCommentsPage.getRecords();
        // 获取评论人信息
        List<Integer> userIdList = records
                .stream()
                .map(ReqComments::getSendId)
                .collect(Collectors.toList());
        List<UserVO> userVOList = userService.listUserVoByIds(userIdList);
        Map<Integer, UserVO> userVOMap = userVOList.stream().collect(Collectors.toMap(UserVO::getId, userVO -> userVO));
        List<RequirementCommentVo> resultList = new ArrayList<>();
        records.forEach(reqComments -> {
            RequirementCommentVo requirementCommentVo = BeanUtil.copyProperties(reqComments, RequirementCommentVo.class);
            UserVO userVO = userVOMap.get(reqComments.getSendId());
            requirementCommentVo.setSendUser(userVO);
            resultList.add(requirementCommentVo);
        });
        Page<RequirementCommentVo> pageResult = new Page<>(current, pageSize);
        BeanUtil.copyProperties(taskCommentsPage, pageResult);
        pageResult.setRecords(resultList);
        return pageResult;
    }
}




